package message

import (
	"encoding/json"
	"github.com/garyburd/redigo/redis"
	"push"
	"rhelper"
	"time"
)

type Message struct {
	MsgId         int    `json:"msgId"`
	MsgType       string `json:"msgType"`
	MsgUser       string `json:"msgUser"`
	MsgCreateTime int64  `json:"msgCreateTime"`
	MsgImg        string `json:"msgImg"`
	MsgTitle      string `json:"msgTitle"`
	MsgContent    string `json:"msgContent"`
	MsgRead       int
}

func GenerateMessageID() (newMessageId int, err error) {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	newMessageId, err = redis.Int(rconn.Do("INCR", rhelper.MsgIdHolder))
	return
}

func GenerateMessages(msgUsers []string, msgType, msgImg, msgTitle, msgContent string, msgRead int) []Message {
	msgs := []Message{}
	for _, msgUser := range msgUsers {
		msg := Message{}
		msg.MsgId, _ = GenerateMessageID()
		msg.MsgUser = msgUser
		msg.MsgType = msgType
		msg.MsgCreateTime = time.Now().Unix()
		msg.MsgImg = msgImg
		msg.MsgTitle = msgTitle
		msg.MsgContent = msgContent
		msg.MsgRead = msgRead

		msgs = append(msgs, msg)
	}

	return msgs
}

func SendMessage(msgs []Message, MessageClass string) error {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	rconn.Send("MULTI")
	accountList := make([]string, 0)
	for _, msg := range msgs {
		//msg.MsgRead = 1
		msgJson, _ := json.Marshal(msg)

		//rconn.Send("LPUSH", rhelper.MsgHash + ":" + MessageClass + ":" + msg.MsgUser , "msgId", msg.MsgId ,
		//	"msgType", msg.MsgType, "msgUser", msg.MsgUser, "msgCreateTime", msg.MsgCreateTime, "msgImg", msg.MsgImg,
		//	"msgTitle", msg.MsgTitle, "msgContent", msg.MsgContent, "msgRead", msg.msgRead)

		rconn.Send("LPUSH", rhelper.MsgHash+MessageClass+":"+msg.MsgUser, msgJson)

		rconn.Send("RPUSH", rhelper.MsgURHash+MessageClass+":"+msg.MsgUser, msg.MsgId)

		accountList = append(accountList, msg.MsgUser)
	}

	push.Send(accountList, msgs[0].MsgTitle)

	rconn.Do("EXEC")

	return nil
}

func SendGmail(to string, msgBody string) {
	if to == "" {
		return
	}

	push.SendGmail(to, msgBody)
}

//
//func SendLogoutMessage(account string, devToken string, os string) {
//	rconn := rhelper.Pool().Get()
//	defer rconn.Close()
//
//	id, err := redis.Int(rconn.Do("INCR", rhelper.MsgIdHolder))
//	if err != nil {
//		log.Println("sendNotify2OriginDevice, get message id err:", err)
//		return
//	}
//
//	msg := Message{}
//	msg.Type = "logout"
//	msg.To = account
//	msg.From = "system"
//	msg.Abstract = "Log exception"
//	msg.Detail = "Account login in another phone"
//	msg.Title = "Account login in another phone"
//	msg.Id = id
//	msg.Stime = int(time.Now().Unix())
//	b, err := json.Marshal(msg)
//	if err != nil {
//		log.Println("SendLogoutMessage, encode error:", err)
//		return
//	}
//
//	go push.SendLogoutMessage(b, msg.Title, devToken, os)
//}
